import DestructibleFacility from "../facility/DestructibleFacility";
import LaunchableFalicity from "../facility/LaunchableFalicity";
import Scout from "../flyer/DestructibleFlyer/Scout";
import Launchable from "../funcObj/interface/Launchable";
import { FacilityType } from "../info/GameEnum";
import { Global } from "../info/Global";
import { Location } from "../info/Predefine";
import NodePoolManager from "../manager/NodePoolManager";
import Player from "../player/Player";

const { ccclass, property } = cc._decorator;

/**
 * 侦察机储备
 */
@ccclass
export default class ScoutReserve extends LaunchableFalicity implements Launchable {
    creat(): void {
    }

    dispatching: boolean;

    fac: DestructibleFacility = null;

    scoutQueue: Array<cc.Node> = null;

    get count(): number {
        return this.scoutQueue.length;
    }

    get locations(): Location[] {
        return this.fac.locations;
    }

    init(player: Player, fac: DestructibleFacility): void {
        this.fac = fac;
        this.player = player;
        this.facilityInfo = Global.getFacilityInfo<any>(FacilityType.侦察机基地);
        this.fac.node.on(DestructibleFacility.EventType.摧毁, this.die, this);
        this.scoutQueue = [];
        this.dispatchQueue = [];
        this.dispatching = false; 

        for (let i = 0; i < 5; i++) {
            let scout: cc.Node = NodePoolManager.instance.obtain(NodePoolManager.instance.scout);
            scout.getComponent(Scout).init(this.fac);
            this.scoutQueue.push(scout);
            let spacePoints = this.node.children;
            let flyerParent = this.fac.player.flyerParentNode;
            scout.parent = flyerParent;
            scout.position = flyerParent.convertToNodeSpaceAR(spacePoints[i].convertToWorldSpaceAR(cc.Vec3.ZERO));
            spacePoints[i]["record"] = scout;
            scout.getComponent(cc.Animation).play("scoutFloat");
        }
        this.fac.player.node.emit(Player.EventType.更新飞行物数量, FacilityType.侦察机基地, 1);
    }

    dispatch(target: Location) {
        let scout: cc.Node = this.scoutQueue.shift();
        let spacePoint = this.node.children.find(item => item["record"] === scout);
        spacePoint["record"] = null;
        this.dispatchQueue.push({ flyer: scout, target: target });
        this.fac.player.node.emit(Player.EventType.更新飞行物数量, FacilityType.侦察机基地, -1);
    }

    /**
     * 如果没有了并且全部发射结束了
     */
    protected autoDispatch(): void {
        super.autoDispatch();
        if (this.count == 0 && this.dispatchQueue.length == 0)
            this.die();
    }


    die() {
        this.fac.node.targetOff(this);
        this.dispatching = false;
        this.dispatchQueue = [];
        NodePoolManager.instance.recycle(this.node);
        this.node.children.forEach(item => item["record"] = null)
        this.scoutQueue = null;
        this.fac = null;
    }
}